package com.jinlia.show.modules.system.auth;

import com.alibaba.fastjson.JSONObject;
import com.jinlia.show.common.core.entity.TokenModer;
import com.jinlia.show.common.core.exception.MyRuntimeException;
import com.jinlia.show.common.core.utils.JavaJwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@RequiredArgsConstructor
@Service
public class AuthService {
    private final JdbcTemplate jdbcTemplate;

    public JSONObject builderToken(LoginRequest loginRequest) {
        //查询用户的sql
        String sql = "select u.id as userId,u.username,u.password from sys_user u " +
                "where u.username = ?";
        List<TokenModer> tokenModerList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(TokenModer.class),
                loginRequest.getUsername());
        if (CollectionUtils.isEmpty(tokenModerList)) {
            throw new MyRuntimeException("账号密码不正确!!!");
        }
        if (!tokenModerList.get(0).getPassword().equals(loginRequest.getPassword())) {
            throw new MyRuntimeException("账号密码不正确!!!");
        }
        JSONObject jsonObject = new JSONObject();
        if (tokenModerList.size() == 1) {
            TokenModer tokenModer = tokenModerList.get(0);
            tokenModer.setCompanyId(tokenModerList.get(0).getCompanyId());
            jsonObject.put("token", JavaJwtUtils.builderCompanyToken(tokenModer));
            jsonObject.put("needSecLogin", false);
        } else {
            jsonObject.put("token", JavaJwtUtils.builderUserToken(tokenModerList.get(0)));
            jsonObject.put("needSecLogin", true);
        }
        return jsonObject;
    }

}
